<template>
    <a-card id="profile">
        <div class="profile-head"></div>
        <div class="profile-banner">
            <div class="profile-top">
                <a-avatar class="avatar-icon" :size="130">
                    <template #icon>
                        <a-icon icon="user-outlined" />
                    </template>
                </a-avatar>
                <div class="profile-user-info">
                    <h2>
                        {{ model.RealName }}
                    </h2>
                    <h4>{{ isStudent() ? "学" : "工" }}号：{{ model.Code }} · {{ app.currentUser.currentRole.DisplayName || "无" }}</h4>
                </div>
            </div>
        </div>
        <a-form class="profile-body" :model="model" :labelCol="{ span: 2 }" :rules="rules" ref="formRef">
            <a-alert class="error" v-if="errors.length" type="error" showIcon :message="`保存个人信息时发生错误：`">
                <template #description>
                    <ul>
                        <li v-for="(v, k) in errors" :key="k">{{ v }}</li>
                    </ul>
                </template>
            </a-alert>
            <a-alert v-if="!errors.length" type="info" showIcon message="若数据有误，请发邮件到jwccxw@xmu.edu.cn修改" />
            <a-spin v-if="profileLoading" tip="加载中..." size="large"/>
            <a-flex v-else vertical>
                <!-- 基本信息 -->
                <div class="profile-body-part">
                    <h2>
                        <a-icon icon="HomeOutlined" /> 基本信息
                    </h2>
                    <a-form-item v-for="(field, index) in [
                        { name: 'UserName', label: '用户名', placeholder: '请输入用户名，此字段必须全系统唯一', maxlength: 50 },
                        { name: 'RealName', label: '姓名', placeholder: '请输入姓名', maxlength: 60 },
                        { name: 'Code', label: isStudent() ? '学号' : '工号', placeholder: `请输入${isStudent() ? '学号' : '工号'}，此字段必须全系统唯一`, maxlength: 30 },
                        { name: 'Mobile', label: '手机', placeholder: '请输入手机号，此字段必须全系统唯一', maxlength: 30 },
                        { name: 'Email', label: '邮箱', placeholder: '请输入邮箱，此字段必须全系统唯一', maxlength: 50 },
                    ]" :key="index" :label="field.label">
                        <span v-if="initailModel[field.name]">{{ model[field.name] }}</span>
                        <a-input v-else v-model:value="model[field.name]" :placeholder="field.placeholder" show-count :maxlength="field.maxlength" />    
                    </a-form-item>
                    <a-form-item name="Gender" label="性别">
                        <span v-if="initailModel.Gender">{{ model.Gender }}</span>
                        <a-radio-group v-else v-model:value="model.Gender">
                            <a-radio-button value="男">男</a-radio-button>
                            <a-radio-button value="女">女</a-radio-button>
                        </a-radio-group>
                    </a-form-item>
                    <a-form-item name="Birthday" label="生日">
                        <span v-if="initailModel.Birthday">{{ model.Birthday }}</span>
                        <date-picker v-else v-model:value="model.Birthday" placeholder="请选择生日" />
                    </a-form-item>
                </div>
                <!-- 学生信息 -->
                <div v-if="isStudent()" class="profile-body-part">
                    <h2>
                        <a-icon icon="SmileOutlined" /> 学生信息
                    </h2>
                    <a-form-item v-for="(field, index) in [
                        { name: 'Grade', label: '年级', placeholder: '请输入年级', maxlength: 10 },
                        { name: 'Major', label: '专业', placeholder: '请输入专业', maxlength: 20 },
                        { name: 'ReformType', label: '教改类型', placeholder: '请输入教改类型', maxlength: 10 },
                        { name: 'Nationality', label: '国籍', placeholder: '请输入国籍', maxlength: 20 },
                        { name: 'Ethnic' , label: '民族', placeholder: '请输入民族', maxlength: 10 },
                        { name: 'BirthPlace', label: '籍贯', placeholder: '请输入籍贯', maxlength: 20 },
                        { name: 'Politics', label: '政治面貌', placeholder: '请输入政治面貌', maxlength: 20 },
                        { name: 'StudentSource', label: '生源地', placeholder: '请输入生源地', maxlength: 20 },
                    ]" :key="index" :label="field.label">
                        <span v-if="initailModel[field.name]">{{ model[field.name] }}</span>
                        <a-input v-else v-model:value="model[field.name]" :placeholder="field.placeholder" show-count :maxlength="field.maxlength" />    
                    </a-form-item>
                    <a-form-item name="GraduadeTime" label="预计毕业时间">
                        <span v-if="initailModel.GraduadeTime">{{ model.GraduadeTime }}</span>
                        <date-picker v-else v-model:value="model.GraduadeTime" placeholder="请选择预计毕业时间" />
                    </a-form-item>
                </div>
                <!-- 老师信息 -->
                <div v-else class="profile-body-part">
                    <h2>
                        <a-icon icon="SmileOutlined" /> 老师信息
                    </h2>
                    <a-form-item v-for="(field, index) in [
                        { name: 'Title', label: '职称', placeholder: '请输入职称', maxlength: 20 },
                        { name: 'Position', label: '职务', placeholder: '请输入职务', maxlength: 20 },
                        { name: 'Education', label: '学历', placeholder: '请输入学历', maxlength: 20 },
                        { name: 'QQ', label: 'QQ号', placeholder: '请输入QQ号', maxlength: 30 },
                        { name: 'OfficePhone', label: '办公室电话', placeholder: '请输入办公室电话', maxlength: 30 },
                    ]" :key="index" :label="field.label">
                        <span v-if="initailModel[field.name]">{{ model[field.name] }}</span>
                        <a-input v-else v-model:value="model[field.name]" :placeholder="field.placeholder" show-count :maxlength="field.maxlength" />    
                    </a-form-item>
                </div>
            </a-flex>
            <a-form-item>
                <a-button class="summit-button" key="submit" type="primary" :loading="submitLoading" @click="onBasicSubmit">提交</a-button>
            </a-form-item>
        </a-form>
    </a-card>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import app from '@/app';
import axios from '@/axios'
import { message } from 'ant-design-vue';
import _ from 'lodash'

const departName = ref("");
let commonRole = app.currentUser.Roles.find(e => e.Name === "普通教师");
if (commonRole) {
    departName.value = commonRole.DepartName;
}

const form = ref();
const empty = {
    "RealName": "",
    "CodeType": "教工号",
    "Code": "",
    "DisplayOrder": 0,
    "Mobile": "",
    "Email": "",
    "UserName": "",
    "OpenId": "",
    "Avatar": "",
    "Level": 3,
    "RootDepartId": app.GUID_EMPTY,
    "LockCount": 0,
    "LockTo": "",
    "AuditStatus": 1,
    "UserSource": "后台添加",
    "Gender": "男",
    "Birthday": "",
    "IsPayroll": false,
    "BankName": "",
    "CardNumber": "",
    "ID": app.GUID_EMPTY,

    "Grade": "",
    "Major": "",
    "Department": "",
    "GraduadeTime": "",
    "ReformType": "",
    "Nationality": "",
    "Ethnic": "",
    "BirthPlace": "",
    "Politics": "",
    "StudentSource": "",
    
    "Title": "",
    "Position": "",
    "Education": "",
    "QQ": "",
    "OfficePhone": "",
};
const model = reactive({ ...empty });
const initailModel = { }
const profileLoading = ref(true);

onMounted(() => {
    if (form.value && form.value.clearValidate) {
        form.value.clearValidate();
    }

    loadUser();
});

async function loadUser() {
    profileLoading.value = true;
    let msg = await axios.post("/api/users/GetProfile");
    if (!msg.success) {
        message.error(msg.msg);
        return;
    }
    Object.assign(model, msg.data);
    Object.assign(initailModel, msg.data);
    profileLoading.value = false;
}

function isStudent() {
    return ['本科生', '研究生', '少数民族预科生'].includes(app.currentUser.currentRole.Name);
}

// -- 登录信息 -- //
const rules = reactive({
    "RealName": [
        { "type": "string", "min": 0, "max": 60, "message": "姓名限60字" },
        { required: true, message: "必须填写姓名" }
    ],
    "Code": [
        { "type": "string", "min": 0, "max": 30, "message": "证件号限30字" },
        { "required": true, "message": "必须填写证件号" },
        {
            validator: function (rule, value, cb, source, options) {
                let userId = model.ID;            
                return new Promise((resolve, reject) => {
                    axios.post("/api/users/CodeValidate", { userId, code: value })
                        .then(msg => {
                            if (msg.success) {
                                resolve();
                            } else {
                                reject(msg.msg);
                            }
                        });
                });
            },
            trigger: 'blur'
        }
    ],
    "DisplayOrder": [
        { "type": "integer", "message": "排序号必须是数字" }
    ],
    "Mobile": [
        { "type": "string", "min": 0, "max": 11, "message": "手机号限11位" },
        { "type": "string", "pattern": "^1[3-9]\\d{9}$", "message": "这不是一个合法的手机号" },
        {
            validator: function (rule, value, cb, source, options) {
                let userId = model.ID;
                return new Promise((resolve, reject) => {
                    axios.post("/api/users/MobileValidate", { userId, mobile: value })
                        .then(msg => {
                            if (msg.success) {
                                resolve();
                            } else {
                                reject(msg.msg);
                            }
                        });
                });
            },
            trigger: 'blur'
        }
    ],
    "Email": [
        { "type": "string", "min": 0, "max": 50, "message": "电子邮箱限50字" },
        { "type": "string", "pattern": "^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$", "message": "这不是一个合法的电子邮箱名称" },
        {
            validator: function (rule, value, cb, source, options) {
                let userId = model.ID;
                return new Promise((resolve, reject) => {
                    axios.post("/api/users/EmailValidate", { userId, email: value })
                        .then(msg => {
                            if (msg.success) {
                                resolve();
                            } else {
                                reject(msg.msg);
                            }
                        });
                });
            },
            trigger: 'blur'
        }
    ],
    "UserName": [
        { "type": "string", "min": 0, "max": 50, "message": "用户名必须小于50字" },
        {
            validator: function (rule, value, cb, source, options) {
                let userId = model.ID;
                return new Promise((resolve, reject) => {
                    axios.post("/api/users/UserNameValidate", { userId, userName: value })
                        .then(msg => {
                            if (msg.success) {
                                resolve();
                            } else {
                                reject(msg.msg);
                            }
                        });
                });
            },
            trigger: 'blur'
        }
    ],
    "BankName": [
        { "type": "string", "min": 0, "max": 40, "message": "银行名称限40字" }
    ],
    "CardNumber": [
        { "type": "string", "min": 0, "max": 19, "message": "银行卡号限19位，请不要输入空格" }
    ],
    "Grade": [
        { "type": "string", "min": 0, "max": 10, "message": "年级限10字" }
    ],
    "Major": [
        { "type": "string", "min": 0, "max": 20, "message": "专业限20字" }
    ],
    "Department": [
        { "type": "string", "min": 0, "max": 30, "message": "系所限30字" }
    ],
    "GraduadeTime": [
        { "type": "string", "min": 0, "max": 10, "message": "预计毕业时间限10字" }
    ],
    "ReformType": [
        { "type": "string", "min": 0, "max": 10, "message": "教改类型限10字" }
    ],
    "Nationality": [
        { "type": "string", "min": 0, "max": 20, "message": "国籍限20字" }
    ],
    "Ethnic": [
        { "type": "string", "min": 0, "max": 10, "message": "民族限10字" }
    ],
    "BirthPlace": [
        { "type": "string", "min": 0, "max": 20, "message": "籍贯限20字" }
    ],
    "Politics": [
        { "type": "string", "min": 0, "max": 20, "message": "政治面貌限20字" }
    ],
    "StudentSource": [
        { "type": "string", "min": 0, "max": 20, "message": "生源地限20字" }
    ],
    "Title": [
        { "type": "string", "min": 0, "max": 20, "message": "职称限20字" }
    ],
    "Position": [
        { "type": "string", "min": 0, "max": 20, "message": "职务限20字" }
    ],
    "Education": [
        { "type": "string", "min": 0, "max": 20, "message": "学历限20字" }
    ],
    "QQ": [
        { "type": "string", "min": 0, "max": 30, "message": "QQ号限30字" }
    ],
    "OfficePhone": [
        { "type": "string", "min": 0, "max": 30, "message": "办公室电话限30字" }
    ]
});
const errors = ref([]);
const submitLoading = ref(false);
const formRef = ref();
async function onBasicSubmit() {
    try {
        form.value = formRef.value;
        await formRef.value.validate();
        let msg = await axios.post("/api/users/SaveProfile", model);
        if (msg.success) {
            Object.assign(model, msg.data);
            Object.assign(initailModel, msg.data);
            errors.value = [];
            message.success("保存成功");
        } else {
            errors.value = msg.errorStrings;
        }
    } catch {} finally {
        submitLoading.value = false;
    }
}
// -- 登录信息 -- //
</script>

<style lang="less">
#profile {
    margin: 24px;
    .ant-card-body {
        padding: 0px;
    }

    .profile-head {
        height: 109px;
        background-image: linear-gradient(45deg, #0081ff, #1cbbb4);
        border-radius: 8px 8px 0 0;
    }

    .profile-banner {
        padding: 24px;
        .profile-top {
            display: flex;
        }
        .avatar-icon {
            background: #0050b3;
            margin-top: -64px;
            position: relative;
            box-shadow: 0px 4px 4px 0px #00000040;
        }

        .profile-user-info {
            padding-left: 20px;
            h2 {
                font-size: 18px;
                color: #212B36;
                font-weight: 700;
            }
            h4 {
                color: #777;
                font-size: 14px;
            }
        }
    }

    .profile-body {
        padding: 0 24px 24px 24px;
        .ant-alert {
            margin-bottom: 24px;
        }

        .profile-body-part {
            margin: 0 32px 32px 8px;
            border-bottom: 1px solid #dddddd;
            h2 {
                margin-bottom: 24px;
                font-size: 18px;
                font-weight: bold;
                color: #333;
                svg {
                    margin-right: 8px;
                }
            }

            label::before, label::after {
                content: none;
            }

            .ant-form-item-label {
                min-width: 80px;
                margin: 0 64px 0 32px;
                text-align: start;
                label {
                    color: #333;
                }
            }

            .ant-form-item-required::after {
                content: "*";
                color: #ff4d4f;
            }
        }

        .summit-button {
            float: right;
            margin: 0 32px;
        }
    }
}
</style>